package com.ligong.gptai.service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RequestCallback;
import org.springframework.web.client.ResponseExtractor;
import org.springframework.web.client.RestTemplate;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;

/**
 * @author lwlianghehe@gmail.com
 * @date 2025/9/11
 */
@Service
@Slf4j
public class AliAIService {
    private ObjectMapper objectMapper = new ObjectMapper(); // object转json json转object

    @Qualifier("aliAiHttpClient")
    @Autowired
    private RestTemplate restTemplate;

    public Map sendText(String model, String message) throws JsonProcessingException {
        String url = "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions";
        Map<String, Object> map = new HashMap<>();
        map.put("model", model);
        Map<String, String> messageMap = new HashMap<>();
        messageMap.put("role", "user");
        messageMap.put("content", message);
        map.put("messages", List.of(messageMap));


        HttpEntity<Map> httpEntity = new HttpEntity<>(map, null); // 这里传body 没有传header

        ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class);
        return objectMapper.readValue(exchange.getBody(), Map.class);
    }

    public void sendText(String model, String message, Boolean stream,
                         Consumer<String> onDelta) {
        String url = "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions";
        Map<String, Object> map = new HashMap<>();
        map.put("model", model);
        Map<String, String> messageMap = new HashMap<>();
        messageMap.put("role", "user");
        messageMap.put("content", message);
        map.put("messages", List.of(messageMap));

        map.put("stream", stream);

        RequestCallback requestCallback = request -> {
            request.getHeaders().setContentType(MediaType.APPLICATION_JSON);
            request.getBody().write(objectMapper.writeValueAsBytes(map));
        };

        // 逐行读取响应：仅处理以 "data:" 开头的 SSE 数据行
        ResponseExtractor<Void> responseExtractor = response -> {
            try (InputStream in = response.getBody();
                 BufferedReader reader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    log.info("chatStream,{}", line); // 调试：观察服务端推送的原始行
                    if (!line.startsWith("data:")) {
                        continue; // 忽略注释或空行
                    }
                    String data = line.substring("data:".length()).trim(); // 截取 json 字符串
                    if ("[DONE]".equals(data)) { // 约定的结束标记
                        break;
                    }
                    try {
                        // AliAI Responses 的分片一般是 JSON，包含 type 与负载
                        Map<String, Object> dataMap = objectMapper.readValue(data, Map.class);
                        List<Map> choices = (List<Map>) dataMap.get("choices");
                        for (Map choice : choices) {
                            Map delta = (Map) choice.get("delta");
                            String content = (String) delta.get("content");
                            if (!"".equals(content) && content != null) {
                                if (onDelta != null) {
                                    onDelta.accept(content); // 回调增量文本
                                }

                            }
                        }
                    } catch (Exception ignore) {
                        // 单个分片解析失败时忽略，避免中断整体流
                    }
                }
            }
            return null;
        };

        restTemplate.execute(url, HttpMethod.POST, requestCallback, responseExtractor);
    }

    public Map createImage(String model, String prompt, Integer n, String size) throws JsonProcessingException {
        String url = "https://dashscope.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation";
        Map<String, Object> map = new HashMap<>();
        map.put("model", model);

        Map input = new HashMap<String, Object>();
        Map<String, Object> messageMap = new HashMap();
        messageMap.put("role", "user");

        messageMap.put("content", List.of(Map.of("text", prompt)));
        input.put("messages", List.of(messageMap));

        map.put("input", input);

        map.put("parameters", Map.of("negative_prompt", "",
                "prompt_extend", true,
                "watermark", true,
                "size", size));


        HttpEntity<Map> httpEntity = new HttpEntity<>(map, null); // 这里传body 没有传header

        ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class);
        return objectMapper.readValue(exchange.getBody(), Map.class);
    }
}
